import { Controller, Post, Inject, Body } from '@midwayjs/core';
import { OrderService } from '../service/order.service';
import { PrismaService } from '../service/prisma.service';
import { WechatService } from '../service/wechat.service';
import {
  ApiTags,
  ApiOperation,
  ApiBody,
  ApiResponse,
  ApiProperty,
} from '@midwayjs/swagger';

class CreateOrderDto {
  @ApiProperty({
    description: '套餐编码',
    enum: ['MONTHLY', 'YEARLY', 'LIFETIME'],
    example: 'MONTHLY',
  })
  planCode: string;

  @ApiProperty({ description: '用户ID', minimum: 1, example: 1 })
  userId: number;
}

class PayDto {
  @ApiProperty({ description: '订单ID', minimum: 1, example: 1 })
  orderId: number;
}

@ApiTags(['Order'])
@Controller('/api/order')
export class OrderController {
  @Inject()
  orderService: OrderService;

  @Inject()
  prisma: PrismaService; // 注入 Prisma 用于查询用户

  @Inject()
  wechatService: WechatService;

  @ApiOperation({ summary: '创建订单' })
  @ApiBody({
    description: '下单参数',
    type: CreateOrderDto,
    examples: {
      default: {
        value: { planCode: 'MONTHLY', userId: 1 },
      },
    },
  })
  @ApiResponse({ status: 200, description: '创建成功' })
  @Post('/create')
  async createOrder(@Body() body: CreateOrderDto) {
    // 在真实应用中，userId 应该从 token 中解析，而不是由前端传递
    // 这里为了 Mock 流程，我们暂时从请求体中获取
    if (!body?.userId) {
      return { success: false, message: '请提供 userId' };
    }

    const user = await this.prisma.user.findUnique({
      where: { id: BigInt(body.userId) },
    });

    if (!user) {
      return { success: false, message: '用户不存在' };
    }

    try {
      const order = await this.orderService.createOrder(user, body.planCode);
      return { success: true, data: order };
    } catch (error) {
      return { success: false, message: error.message };
    }
  }

  /**
   * 发起支付 - 调用微信统一下单接口
   */
  @ApiOperation({ summary: '发起支付' })
  @ApiBody({
    description: '支付参数',
    type: PayDto,
    examples: {
      default: { value: { orderId: 1 } },
    },
  })
  @ApiResponse({ status: 200, description: '返回微信支付参数' })
  @Post('/pay')
  async pay(@Body() body: PayDto) {
    if (!body?.orderId) {
      return { success: false, message: '请提供 orderId' };
    }

    try {
      // 查询订单
      const order = await this.prisma.order.findUnique({
        where: { id: BigInt(body.orderId) },
        include: { user: true, plan: true },
      });

      if (!order) {
        return { success: false, message: '订单不存在' };
      }

      if (order.status !== 0) {
        return { success: false, message: '订单状态不正确' };
      }

      // 调用微信统一下单
      const payParams = await this.wechatService.createUnifiedOrder(
        order.user.openid,
        order.amount, // 金额已经是分了，不需要再乘100
        order.plan.name || '会员服务',
        order.orderNo
      );

      return { success: true, data: payParams };
    } catch (error) {
      console.error('支付失败:', error);
      return { success: false, message: error.message };
    }
  }
}
